package groupb6.shopsystem.service.impl;


import groupb6.shopsystem.config.DyMessageConfig;
import groupb6.shopsystem.mapper.NotificationMapper;
import groupb6.shopsystem.mapper.OrderMapper;
import groupb6.shopsystem.mapper.StoreMapper;
import groupb6.shopsystem.mapper.UserMapper;
import groupb6.shopsystem.pojo.entity.Notification;
import groupb6.shopsystem.pojo.entity.Order;
import groupb6.shopsystem.pojo.entity.Store;
import groupb6.shopsystem.pojo.entity.User;
import groupb6.shopsystem.service.AdminService;
import groupb6.shopsystem.util.enums.OrderStatusEnum;
import groupb6.shopsystem.util.enums.ResponseEnum;
import groupb6.shopsystem.util.enums.StoreStatusEnum;
import groupb6.shopsystem.util.response.UniversalResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private NotificationMapper notificationMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DyMessageConfig dyMessageConfig;
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据店铺id查询店铺信息
     *
     * @param id 店铺id
     * @return 店铺信息
     */
    @Override
    public UniversalResponse<Store> getStoreDetailByStoreId(Integer id) {
        Store store1 = storeMapper.selectById(id);
        if (store1 == null) {
            return new UniversalResponse<>(7000, "店铺不存在");
        }
        return new UniversalResponse<>(1000, "成功", store1);
    }

    /**
     * 查询符合状态条件的店铺信息
     *
     * @param status 店铺状态
     * @return 店铺列表
     */
    @Override
    public UniversalResponse<List<Store>> getStoresByStatus(Integer status) {
        List<Store> stores = storeMapper.getStoreByStatus(status);
        if (stores == null) {
            return new UniversalResponse<>(7000, "店铺不存在");
        }
        return new UniversalResponse<>(1000, "成功", stores);
    }

    /**
     * 审批店铺
     *
     * @param storeId 店铺id
     * @param approve 是否通过审批
     * @param userId  发送者id
     * @return 处理结果
     */
    @Override
    public UniversalResponse<?> approveStore(Integer storeId, Boolean approve, Integer userId) {
        Store store = storeMapper.selectById(storeId);
        if (store == null) {
            return new UniversalResponse<>(7000, "店铺不存在");
        }
        if (store.getStatus().equals(StoreStatusEnum.NOT_PROCESSED.getStatus())) {
            //未审批状态
            //store.setStatus(StoreStatusEnum.ACCEPTED.getStatus());
            if (approve) {
                //通过审批
                store.setStatus(StoreStatusEnum.ACCEPTED.getStatus());
                notifySeller(storeId, true);
            } else {
                //未通过审批
                store.setStatus(StoreStatusEnum.NOT_ACCEPTED.getStatus());
                notifySeller(storeId, false);
            }
            storeMapper.updateById(store);
            return new UniversalResponse<>(1000, "成功");
        } else {
            return new UniversalResponse<>(7001, "店铺无需批准");
        }
    }

    /**
     * 返回全部店铺信息
     *
     * @return 店铺数组
     */
    @Override
    public UniversalResponse<List<Store>> getAllStore() {
        List<Store> stores = storeMapper.getAllStores();
        return new UniversalResponse<>(1000, "成功", stores);
    }

    @Override
    public void notifySeller(Integer storeId, Boolean approval) {

        Store store1 = storeMapper.selectById(storeId);
        Notification notification1 = new Notification();
//        Message newMessage = new Message();
//        newMessage.setId(null);
//        newMessage.setSendId(adminId);
//        newMessage.setReceiveId(store1.getSellerId());
//        newMessage.setTime(new Timestamp(System.currentTimeMillis()));
        notification1.setStatus(null);
        notification1.setId(null);
        notification1.setTitle("approve result");
        notification1.setUserId(store1.getSellerId());
        if (approval) {
            notification1.setDetail("Your store has been approved.");
        } else {
            notification1.setDetail("Your store wasn't approved.");
        }
        notificationMapper.insert(notification1);
        try {
            this.sendDyMessage(store1.getSellerId(), approval);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public UniversalResponse<List<Order>> listShippedOrders() {
        List<Order> orders = orderMapper.listShippedOrders();
        return new UniversalResponse<>(ResponseEnum.SUCCESS.getCode(),
                ResponseEnum.SUCCESS.getMsg(),
                orders);
    }

    @Override
    public UniversalResponse<?> deliveredShippedOrders() {
        orderMapper.deliveredShippedOrders();
        return new UniversalResponse<>(ResponseEnum.SUCCESS.getCode(),
                ResponseEnum.SUCCESS.getMsg());
    }

    @Override
    public UniversalResponse<?> orderDelivered(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            ResponseEnum res = ResponseEnum.ORDER_NOT_FOUND;
            return new UniversalResponse<>(res.getCode(), res.getMsg());
        }
        if (!order.getStatus().equals(OrderStatusEnum.SHIPPED.getStatus())) {
            ResponseEnum res = ResponseEnum.ORDER_ERROR;
            return new UniversalResponse<>(res.getCode(), res.getMsg());
        }
        order.setStatus(OrderStatusEnum.DELIVERED.getStatus());
        orderMapper.updateById(order);
        ResponseEnum res = ResponseEnum.SUCCESS;
        return new UniversalResponse<>(res.getCode(), res.getMsg());
    }

    /**
     * 调用阿里云短信服务
     *
     * @param toUserId 接收短信用户id
     * @param result   审批结果 通过true，不通过false
     */
    @Override
    public void sendDyMessage(Integer toUserId, Boolean result) throws Exception {
        User currentUser = userMapper.selectById(toUserId);
        if (currentUser.getTel() == null || currentUser.getTel().length() != 11) {
            //如果手机号为空，或者手机号不正确,直接返回
            return;
        }
        com.aliyun.dysmsapi20170525.Client client = this.createClient();

        String resultStr = (result) ? "approved" : "rejected";
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("OnlineShop")
                .setTemplateCode("SMS_465961208")
                .setPhoneNumbers(currentUser.getTel())
                .setTemplateParam("{\"nickName\":\"" + currentUser.getName() + "\", \"result\":\"" + resultStr + "\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        client.sendSmsWithOptions(sendSmsRequest, runtime);
    }

    /**
     * 获取短信服务客户端
     *
     * @return 短信客户端
     * @throws Exception 发生错误
     */
    private com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(dyMessageConfig.getAccessKey())
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(dyMessageConfig.getAccessKeySecret());
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}
